<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission('0', 1)">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(scope.row.id, 2)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delFunction(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog title="新增权限点" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="addOrEditHandle">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getPermissionList,
  addPermission,
  updatePermission,
  getPermissionDetail,
  delPermission
} from '@/api/permission'
import { transTree } from '@/utils/index'
export default {
  name: 'Permission',
  //   name自定义校验规则
  data() {
    const validName = (rule, value, callback) => {
      // 查找同级元素
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      // 编辑时的验证
      // 分析：还是需要筛选出同级的权限点，只不过需要将本身排除
      if (this.isEdit) {
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 拿用户输入的值和同级的权限点中的 name 进行比对
      // 将统计权限点的 name 组成一个新的数组，使用 includes 方法进行验证
      existNameList.map(item => item.name).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }

    // code自定义验证
    const validCode = (rule, value, callback) => {
      let existCodeList = this.originList
      // 判断是不是编辑
      if (this.isEdit) {
        //   去除本身
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      //   通过includes属性 查看value是否和item.code的值相同 如果是 就提示已存在 如果不是就放行
      existCodeList.map(item => item.code).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }

    return {
      permissionList: [], // 权限列表
      showDialog: false, // 是否展示新增/编辑权限弹框
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 是否是编辑
      roleId: '', // 当前权限的 ID
      originList: [] // 接收新数组

    }
  },

  created() {
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 删除功能
    async delFunction(id) {
      const confirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //   console.log(confirm)
      //   删除成功是confirm 取消删除是cancel
      // 所有判断是否取消删除
      if (confirm === 'cancel') return this.$message('您已取消删除')
      //  确认删除
      const res = await delPermission(id)
      //   删除成功提示
      this.$message.success(res.message)
      this.getPermissionList()
      console.log(res)
    },
    //   编辑功能
    async editPermission(id) {
      this.roleId = id
      this.isEdit = true
      const res = await getPermissionDetail(this.roleId)
      this.formData = res.data
      this.showDialog = true

    //   console.log(res)
    },
    //   确定按钮
    addOrEditHandle() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return
        // 判断是不是编辑
        if (this.isEdit) {
          await updatePermission(this.formData)
        //   console.log(res)
        } else {
          await addPermission(this.formData)
          // console.log(res)
        }
        this.$message.success(this.isEdit ? '编辑成功' : '添加成功')
        this.showDialog = false
        this.getPermissionList()
      })
    },

    // 添加权限
    addPermission(pid, type) {
    //   console.log(pid, type)
      this.formData.pid = pid
      this.formData.type = type
      this.isEdit = false
      this.showDialog = true
      //   编辑权限的弹窗
    },

    //   取消
    btnCancel() {
      this.showDialog = false
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      //   console.log(res)
      this.originList = res.data.map(item => ({
        id: item.id,
        pid: item.pid,
        code: item.code,
        name: item.name.trim()
      }))

      this.permissionList = transTree(res.data, '0')
    //   console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped></style>
